﻿using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace WPFServices.ViewModels
{
    /// <summary>
    /// 所有ViewModel的基类，实现属性变更通知
    /// </summary>
    public class BaseViewModel : INotifyPropertyChanged
    {
        // 属性变更事件，当属性值改变时通知UI更新
        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        /// 通知属性已更改，触发UI更新
        /// </summary>
        /// <param name="propertyName">属性名称，自动获取</param>
        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        /// <summary>
        /// 设置属性值并通知更改
        /// </summary>
        protected virtual bool SetProperty<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
        {
            if (Equals(field, value)) return false;
            field = value;
            OnPropertyChanged(propertyName);
            return true;
        }
    }
}